/*
 * @Author: 悦者生存 1002783067@qq.com
 * @Date: 2023-03-12 20:28:07
 * @LastEditors: 悦者生存 1002783067@qq.com
 * @LastEditTime: 2023-04-13 23:22:29
 * @FilePath: /koa2-ts-template/src/middlewares/static.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import koa from 'koa';
import path from 'path';
import fs from 'fs-extra';

export const staticFile = (staticDir: string) => {
  return async (ctx: koa.Context, next: Function) => {
    await next();
    if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return;
    if (ctx.body !== null && ctx.status !== 404) return;
    try {
      const pathname = ctx.request.url;
      const realFilePath = path.join(staticDir, pathname);
      const fileReadStream = fs.createReadStream(realFilePath);
      ctx.type = path.extname(pathname);
      ctx.body = fileReadStream;
    } catch (error) {
      console.log(error);
      throw new Error('获取文件失败');
    }
  };
};
